import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import type { MenuProps } from "antd";
import { Button, Dropdown, Avatar, Modal, Form, Input, message } from "antd";
import { UserOutlined } from "@ant-design/icons";
import { cleanToken, cleanUserInfo, cleanPermissions } from "@/stores/actions";
import { stores } from "@/stores";
import { $post, $get } from "@/api/RestUtils";
import { encrypt } from "@/utils/RSAUtils";
import { useDispatch, useSelector } from "react-redux";
import "./index.less";

const App: React.FC = () => {
  const [passForm] = Form.useForm();
  const [modal, contextHolder] = Modal.useModal();

  const title = useSelector((state: any) => state.title);
  const avatarPath = useSelector((state: any) => state.userInfo.avatarPath);

  const [resetPassModalShow, setResetPassModalShow] = useState(false);

  const navigate = useNavigate();
  const dispatch = useDispatch();

  const items: MenuProps["items"] = [
    {
      key: "1",
      label: <div onClick={() => setResetPassModalShow(true)}>修改密码</div>,
    },
    {
      key: "2",
      label: <div onClick={() => logoutConfirm()}>退出登录</div>,
    },
  ];

  const checkRepeatPass = (_: any, value: string) => {
    if (value != passForm.getFieldValue("newPass")) {
      return Promise.reject(new Error("两次输入密码不一致"));
    } else {
      return Promise.resolve();
    }
  };

  const changePass = (formData: any) => {
    formData.oldPass = encrypt(formData.oldPass);
    formData.newPass = encrypt(formData.newPass);
    formData.checkPass = encrypt(formData.checkPass);
    $post("/user/changePass", formData)
      .then((res: any) => {
        if (res.code === 0) {
          dispatch(cleanToken());
          message.success(res.msg);
          navigate("/login");
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const logoutConfirm = () => {
    modal.confirm({
      title: "是否退出登录？",
      okText: "确认",
      cancelText: "取消",
      onOk: () => logout(),
    });
  };

  const logout = () => {
    $get("/user/logout", null)
      .then((res: any) => {
        if (res.code === 0) {
          dispatch(cleanToken());
          dispatch(cleanUserInfo());
          dispatch(cleanPermissions());
          message.success(res.msg);
          navigate("/login");
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const closePassModal = () => {
    setResetPassModalShow(false);
    passForm.resetFields();
  };
  const resetPassForm = () => {
    passForm.resetFields();
  };

  return (
    <>
      {contextHolder}
      <Modal
        title="修改密码"
        open={resetPassModalShow}
        onCancel={closePassModal}
        footer={null}
      >
        <Form
          form={passForm}
          labelAlign="right"
          layout="vertical"
          colon={false}
          onFinish={changePass}
        >
          <Form.Item
            name="oldPass"
            label="原密码"
            validateFirst
            rules={[
              { required: true, type: "string", message: "请输入原密码" },
              { max: 16, min: 8, message: "长度在8~16位" },
            ]}
          >
            <Input type="password" placeholder="原密码" maxLength={16} />
          </Form.Item>
          <Form.Item
            name="newPass"
            label="新密码"
            validateFirst
            rules={[
              { required: true, type: "string", message: "请输入新密码" },
              { max: 16, min: 8, message: "长度在8~16位" },
            ]}
          >
            <Input type="password" placeholder="新密码" maxLength={16} />
          </Form.Item>
          <Form.Item
            name="checkPass"
            label="重复新密码"
            validateFirst
            rules={[
              { required: true, type: "string", message: "请重复输入新密码" },
              { max: 16, min: 8, message: "长度在8~16位" },
              { validator: checkRepeatPass },
            ]}
          >
            <Input type="password" placeholder="重复新密码" maxLength={16} />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
            <Button onClick={resetPassForm}>重置</Button>
          </Form.Item>
        </Form>
      </Modal>
      <div className="header-flex">
        <div className="header-breadcrumb">{title}</div>
        <div className="operation-area">
          <Dropdown
            overlayClassName="operation-item"
            menu={{ items }}
            placement="bottomLeft"
          >
            <Avatar
              className="user-avatar"
              size={40}
              src={import.meta.env.VITE_REMOTE_FILE_URL + avatarPath}
              icon={<UserOutlined />}
            />
          </Dropdown>
        </div>
      </div>
    </>
  );
};

export default App;
